/**
 * Created by weng on 2018/1/16.
 */

const sea = require('../common/sea');
const request = require('../common/Request');
const RequestPost = request.RequestPost
const RequestPostFom = request.RequestPostFom
const RequestGet = request.RequestGet
const sqlOrm = require('../common/sqlModel');
const apiClient = require('../lib/api/topClient.js').TopClient;
const utils = require("../common/utils")
const mm = require("../common/config").mm
const AppKey = require("../common/config").AppKey
const AppSecret = require("../common/config").AppSecret
const config = require("../common/config")
let webdriver = require('selenium-webdriver');

let loginFlag = 0;
let lastCode
let ServefUrl = "http://127.0.0.1:8083/v01/taobao/saveUrl"
let changeGlobalUrl = "http://127.0.0.1:8083/v01/taobao/changeGlobalUrl"
let vekey = "V00000355Y39162829";


const fs = require('fs');
const  path = require("path")

let client = new apiClient({
    'appkey': AppKey,
    'appsecret': AppSecret,
    'REST_URL': 'http://gw.api.taobao.com/router/rest'
});

const answerUrl = 'http://www.jinyupay.top:8081/'
const transferUrl = 'http://127.0.0.1:18082/v01/paycenter/transfer'

class Register {
    // 存订单信息
    async saveOrder(req, res, body, cb) {
        try {
            let shopId = body.shopId;  //店铺id
            let mainOrderID = body.mainOrderId; //订单id
            let orderIds = body.orderIds; //子订单id
            let itemIds = body.itemIds;  //物品id
            let skuIds = body.skuIds;  //物品小类
            let userId = body.userId; //用户id （电话号码）

            skuIds = utils.changeToObj(skuIds)
            itemIds = utils.changeToObj(itemIds)
            orderIds = utils.changeToObj(orderIds)

            if (!shopId || !mainOrderID || !orderIds || !itemIds || !skuIds || !userId) {
                return cb({code: 500, msg: "参数不足"})
            }
            let orderInfo = await sqlOrm.order.findAsync({taobaoTradeParentId: mainOrderID})
            if (orderInfo.length > 0) {
                return cb({code: 200})
            }
            let orderInfos = [];
            for (var i = 0; i < orderIds.length; i++) {

                // for (var i = 0; i < orderIds.length; i++) {
                orderInfos.push({
                    taobaoTradeParentId: mainOrderID,
                    taobaoTradeSubId: orderIds[i],
                    shopID: shopId,
                    auctionId: itemIds[i],
                    skuId: skuIds[i],
                    userId: userId,
                })
            }
            await sqlOrm.order.createAsync(orderInfos);
            return cb({code: 200})

        } catch (e) {
            console.error("saveOrder err is", e);
            if (!e) e = "err"
            return cb({code: 500, msg: JSON.stringify(e)})
        }
    }

    // 保存搜过的内容
    async saveSearch(req, res, body, cb) {
        try {
            let msg = body.msg;  //店铺id

            if (!msg) {
                return cb({code: 500, msg: "参数不足"})
            }
            let orderInfo = await sqlOrm.searchMsg.findAsync({msg: msg});
            if (orderInfo.length > 0) {
                return cb({code: 200})
            }

            await sqlOrm.searchMsg.createAsync({msg:msg});
            return cb({code: 200})

        } catch (e) {
            console.error("saveOrder err is", e);
            if (!e) e = "err"
            return cb({code: 500, msg: JSON.stringify(e)})
        }
    }

    async chagneGlobal(req, res, cb) {
        try {
            let SqlUrl = await sqlOrm.global.findAsync({type: 1});
            if (SqlUrl.length > 0) {
                global.rate = SqlUrl[0].value
                return cb({code: 200})
            } else {
                return cb({code: 500})
            }
        } catch (e) {
            if (!e) e = "err"
            return cb({code: 500, msg: e})
        }
    }

    async saveUrl(req, res, body, cb) {
        try {
            let SqlUrl = await sqlOrm.tokenUrl.findAsync({});
            body = utils.changeToObj(body)
            // console.log("存库？", body)
            // console.log("存库？", body.codeUrl)
            if (SqlUrl.length <= 0) {

                await sqlOrm.tokenUrl.createAsync({url: body.codeUrl})
            } else {
                SqlUrl[0].url = body.codeUrl
                SqlUrl[0].saveAsync()
            }
            return cb({code: 200, rul: body.codeUrl})
        } catch (e) {
            if (!e) e = "err"
            return cb({code: 500, msg: e})
        }
    }

    async getGeneralizeUrl(req, res, body, cb) {
        try {
            let itemId = body.itemId
            let userId = body.userId;
            let account = body.account;
            let channel = body.channel;
            if (!userId){
                userId = account
            }

            if (!userId || !itemId) {
                return cb({code: 500, msg: "参数不足"})
            }

            let accountInfo = await sqlOrm.app_account.findAsync({account: userId});
            if (accountInfo.length <= 0) {
                return cb({code: 500, info: "没有账信息"})
            }

            switch (channel){
                case "taobao" :
                    GetTaobaoUrl(itemId, userId,accountInfo,cb)
                    break
                case "pdd" :
                    GetPingDDUrl(itemId, userId,accountInfo,cb)
                    break
                default :
                    GetTaobaoUrl(itemId, userId,accountInfo,cb)
                    // return cb({code: 500, info: "渠道不对"})
            }
        } catch (e) {
            if (!e) e = 10 * "err"
            return cb({code: 500, msg: e})
        }
    }

    async getQrCodeUrl(req, res, body, cb) {
        try {
            let url = await sqlOrm.tokenUrl.findAsync({})
            // console.log("dddddddddddddddddddddddddd", url)
            // console.log("dddddddddddddddddddddddddd", url.length)
            if (url.length > 0) {
                let codeUrl = url[0].url
                cb({code: 200, url: codeUrl})
                url[0].remove()
            } else {
                cb({code: 201, msg: "登录中"})
            }

        } catch (e) {
            if (!e) e = "err"
            return cb({code: 500, msg: e})
        }
    }


    async getQrCode(req, res, body, cb) {
        try {

            let cookies = {
                '_tb_token_': this.lgToken,
                't': new Date().getTime(),
                'v': '0',
                'cookie2': global.cookie2,
            };
            let cookie_val = utils.formatCook(cookies);
            let headers = {
                'authority': 'pub.alimama.com',
                'method': 'GET',
                'path': '/common/code/getAuctionCode.json?auctionid=575830334240&adzoneid=78346129&siteid=23532937&scenes=1&tkFinalCampaign=1&t=' + new Date().getTime() + '&_tb_token_=' + this.lgToken + '&pvid=10_47.98.122.59_622_' + new Date().getTime(),
                // 'referer': 'https://pub.alimama.com/promo/search/index.htm?q=%E5%93%87%E5%93%88%E5%93%88ad%E9%92%99%E5%A5%B6220ml&_t=1536243536417&toPage=1&dpyhq=1',
                'x-requested-with': 'XMLHttpRequest',
                'Cookie': cookie_val,
            };

            let isLogin = await RequestGet("http://pub.alimama.com/common/getUnionPubContextInfo.json", {}, headers);
            console.log("is login .....",isLogin);
            isLogin = utils.changeToObj(isLogin);
            // console.log("-------------------------------------------------------------------------", isLogin)
            if (isLogin.code || isLogin.code == 500) {
                // 判断为已经登陆就可以 loginFlag = 0
                loginFlag = 0
                return
            }
            if (!isLogin.data || !isLogin.data.mmNick) {
                // console.log("================================", loginFlag, lastCode)

                if (loginFlag == 1) {
                    return cb({code: 201})
                }
                loginFlag = 1;

                setTimeout(function () {
                    loginFlag = 0
                },10 * 60 * 1000)

                let params = {
                    'from': 'alimama',
                    'appkey': "00000000",
                    '_ksTS': new Date().getTime(),
                };
                let url = 'https://qrlogin.taobao.com/qrcodelogin/generateQRCode4Login.do?'
                let headers = {
                    'authority': 'qrlogin.taobao.com',
                    'method': 'GET',
                    'path': '/qrcodelogin/generateQRCode4Login.do?from=alimama&appkey=00000000&_ksTS=' + new Date().getTime(),
                    'referer': 'https://login.taobao.com/member/login.jhtml?style=mini&newMini2=true&css_style=alimama&from=alimama&redirectURL=http%3A%2F%2Fwww.alimama.com&full_redirect=true&disableQuickLogin=true',
                };

                let QrInfo = await  RequestGet(url, params, headers);
                QrInfo = utils.changeToObj(QrInfo)
                // console.log("QrInfo is:", QrInfo);
                if (QrInfo.lgToken) {
                    this.lgToken = QrInfo.lgToken;
                    let codeUrl = "https://login.m.taobao.com/qrcodeCheck.htm?lgToken=" + QrInfo.lgToken + "&tbScanOpenType=Notification";

                    let b = await  RequestGet(ServefUrl + "?codeUrl=" + codeUrl, {});
                    console.log("33333333333333333333", b)
                    b = utils.changeToObj(b)
                    if (b.code != 200) {
                        loginFlag = 0;
                        return
                    }
                    await login(QrInfo.lgToken);

                    // console.log("codeUrl", codeUrl);
                    cb({code: 200, url: codeUrl})
                } else {
                    return cb({code: 500})
                }
            } else {
                cb({code: 201, msg: "已经登陆"})
            }
        } catch (e) {
            if (!e) e = "err"
            return cb({code: 500, msg: e})
        }
    }

    async getadzoneIdInfo (userId,flag) {
        let url = 'https://pub.alimama.com/common/adzone/selfAdzoneCreate.json';
        var t = new Date().getTime()
        let params = {
            'tag': '29',
            'gcid': "7",
            'siteid': '112300025',
            'selectact': 'add',
            'newadzonename': userId,
            't': t,
            '_tb_token_':global.token,
            'pvid': '10_220.200.59.244_622_' + t,
        };

        let cookies = {
            '_tb_token_': global.token,
            't': "7013840eaba71bb502e4b38f6c792db6",
            'v': '0',
            'cookie2': global.cookie2,
        };
        let cookie_val = utils.formatCook(cookies);
        let headers = {
            'origin': 'https://pub.alimama.com',
            'authority': 'pub.alimama.com',
            'method': 'POST',
            'path': '/common/adzone/selfAdzoneCreate.json',
            'referer': 'https://pub.alimama.com/promo/search/index.htm?q=asd&_t=1537547202752',
            'x-requested-with': 'XMLHttpRequest',
            "Cookie": cookie_val
        }

        // console.log("cookie_val", cookie_val)
        // request.cookie('cookie_val')
        let selfAdzoneCreate = await RequestPostFom(url, params, headers);
        selfAdzoneCreate = utils.changeToObj(selfAdzoneCreate)
        // console.log("selfAdzoneCreate", selfAdzoneCreate)

        var adzoneId = -1;
        if (selfAdzoneCreate.data) {
            adzoneId = selfAdzoneCreate.data.adzoneId;
        }else if(!flag) {
            // 需要重新添加（或者改名字）
            let adzoneIds = await sqlOrm.EXadzoneid.findAsync({},1);
            if (adzoneIds.length >0 ){
                adzoneId = adzoneIds[0].adzoneid
                adzoneIds[0].remove();
                // await sqlOrm.needGetUserId.createAsync({id:userId,adzoneid:adzoneId})
            }
        }
        if(adzoneId == -1 && userId.length <= 11 ){
            await sqlOrm.needGetUserId.createAsync({id:userId,adzoneid:adzoneId})
        }
        return adzoneId
    }


    /*
    * 修改密码
    * */
    async changePassWd (req, res, body, cb) {
        try {
            let account = body.account;  //玩家信息
            let newPass = body.newPass
            let oldPass = body.oldPass
            if(!account || !newPass || !oldPass){
                return cb({code:500,msg:"参数不足"})
            }
            let userInfo = await  sqlOrm.app_account.findAsync({account:account,passWd :oldPass})
            // console.log("userInfo.length",userInfo.length)
            if(userInfo.length <= 0){
                return cb({code:500,msg:"旧密码不正确"})
            }
            var userMine = userInfo[0]
            userMine.passWd = newPass

            userMine.saveAsync();
            return cb({code:200,info:"修改成功"})
        }catch (e) {
            console.error("修改密码 error ",e);
            return cb({code:500,msg:"错误"})
        }
    }

    /*
    * 重新获取golden
    * */
    async changeGlobalUrl (req, res, body, cb) {
        try {
            let CookieInfo  = await sqlOrm.global.findAsync({id:2})
            let tokenInfo = await sqlOrm.global.findAsync({id:3})

            global.cookie2 = CookieInfo[0].value;;
            global.token = tokenInfo[0].value;

            return cb({code:200,info:"修改成功"})
        }catch (e) {
            console.error("修改密码 error ",e);
            return cb({code:500,msg:"错误"})
        }
    }

    /*
    * 获取订单信息
    * */
    async getOrderInfo (req, res, body, cb) {
        try {
            let account = body.account;  //玩家信息 (电话号码)
            let payType = body.payType  //支付状态
            let page = body.page  //页
            let pageSize = body.pageSize  //页数量

            let offet =  JSON.parse((page -1) * pageSize);
            pageSize = JSON.parse(pageSize)
            if(!account){
                return cb({code:500,msg:"参数不足"})
            }
            let conditions
            if(payType != 0){
                if(payType == 2 || payType == 3)
                    payType = [2,3];

                conditions = {userId:account,payStatusCode:payType,share:1}
            }else {
                conditions= {userId:account,share:1}
            }
            let orderInfo = await  sqlOrm.taobaokeOrder.findAsync(conditions,{ offset: offet },pageSize,["createTime","Z"])
            if(orderInfo.length <= 0){
                return cb({code:500,msg:"没有订单信息"})
            }
            for(var i =0;i<orderInfo.length ;i++){
                orderInfo[i].totalAlipayFeeString = JSON.parse(orderInfo[i].totalAlipayFeeString).toFixed(2)
            }
            let res = orderInfo
            return cb({code:200,info:res})
        }catch (e) {
            console.error("getOrderInfo error ",e)
            return cb({code:500,msg:"错误"})
        }
    }


    /*
    * 保存用信息
    * */
    async saveUserInfo (req, res, body, cb) {
        try {
            // console.log("dddddddddddddddddddd",body)
            let userId = body.account;  //玩家信息 (电话号码)

            let base64 = body.icon  //图片内容
            let nick = body.nick  //昵称
            let sex = body.sex  //性别
            let borth = body.borth  //性别
            let aliAccount = body.aliAccount  //性别
            let realName = body.realName  //性别

            if(!userId || (!base64 && !nick && !sex && !borth && !aliAccount && !realName)){
                return cb({code:500,msg:"参数不足"})
            }
            let AccountInfo =await sqlOrm.app_account.findAsync({account:userId});
            if(AccountInfo.length <= 0){
                return cb({code:500,msg:"账号不存在"})
            }
            if(base64){
                let nowTime = new Date().getTime()
                let dirPath = path.join(__dirname, "../public/images");
                dirPath = path.join(dirPath, userId + nowTime + ".png");
                let dataBuffer = new Buffer(base64, 'base64'); //把base64码转成buffer对象，
                // console.log('dataBuffer是否是Buffer对象：'+Buffer.isBuffer(dataBuffer));
                fs.writeFileSync(dirPath,dataBuffer);
                AccountInfo[0].icon = "/images/" + userId +nowTime + ".png"
            }
            if(nick){
                AccountInfo[0].nick =nick
            }
            if(sex){
                AccountInfo[0].sex =sex
            }
            if(borth){
                AccountInfo[0].borth =borth
            }
            if(aliAccount){
                AccountInfo[0].aliAccount =aliAccount
            }

            if(realName){
                AccountInfo[0].realName =realName
            }

            AccountInfo[0].saveAsync();
            return cb({code:200,info:"成功"})
            // fs.writeFile(dirPath,dataBuffer,function(err){//用fs写入文件
            //     if(err){
            //         console.error(err);
            //         return cb({code:500,info:"保存失败"})
            //     }else{
            //         AccountInfo[0].icon = "/images/" + userId + ".png"
            //         AccountInfo[0].saveAsync();
            //         return cb({code:200,info:"保存成功"})
            //     }
            // })


        }catch (e) {
            console.error("saveUserInfo error ",e)
            return cb({code:500,msg:"错误"})
        }
    }





    /*
    * 获取转账日志
    * */
    async getTransLog (req, res, body, cb) {
        try {
            let account = body.account;  //玩家信息 (电话号码)
            let type = body.type;
            let page =  body.page;
            let pageSize = body.pageSize;

            if(page) {}page = utils.changeToObj(page)
            if(pageSize) pageSize = utils.changeToObj(pageSize)
            // console.log("page",page)
            // console.log("pageSize",pageSize)
            let offet = (page -1) * pageSize


            // console.log("type",offet)
           let condition = {AccountID:account}
           if(!!type && type != -1){
                condition = {AccountID:account,status:type}
           }

            let info = await sqlOrm.transfer.findAsync(condition,{ offset: offet },pageSize,["time","Z"])
            if (info.length > 0) return cb({code:200,info:info})
            return cb({code:500,msg:"没有数据"})

        }catch (e) {
            console.error("getTransLog error ",e)
            return cb({code:500,msg:"错误"})
        }
    }


    /*
    *  依据内容查询
    * */



    async findByMsg(req, res, body, cb) {
        try {
            let msg = body.msg
            let account = body.account;
            let page = body.page;
            let pageSize = body.pageSize;
            let coupon = body.coupon;
            let channel = body.channel;
            let sortType = body.sortType;
            let start_price  = body.start_price ;
            let end_price   = body.end_price  ;

            if(!body.sortType || body.sortType =='null'){
                sortType = "total_sales_des"
            }
            if (!account || !msg || !page || !pageSize) {
                return cb({code: 500, msg: "参数不足"})
            }

            let accountInfo = await sqlOrm.app_account.findAsync({account: account});
            if (accountInfo.length <= 0) {
                return cb({code: 500, info: "没有账信息"})
            }
            let mm = accountInfo[0].mm;
                console.log("数据库没有信息调用aip");


        findUrlByAPIMsg(mm, msg, account,page,pageSize, sortType,coupon,start_price,end_price,function (findUrlByAPIRes) {
            if (findUrlByAPIRes.length > 0 ){
                return cb({code: 200, info: findUrlByAPIRes})
            }else {
                console.log("还是没有表示该物品没有推广");
                return cb({code: 202, info: [], msg: "暂时没有信息"})
            }
        })


        } catch (e) {
            if (!e) e = 10 * "err"
            return cb({code: 500, msg: e})
        }
    }

    /*
    * 热销高佣金
    * */
    async hotProducts(req, res, body, cb) {
        try {
            let account = body.account;
            let subcate = body.subcate
            let macId = body.MacId
            let material_id = body.material_id
            let topcate = body.topcate
            let page = body.page
            let pagesize = body.pageSize
            let sort   = body.sort

            if(!account || ! page || !pagesize){
                return cb({code:500,msg:"参数不足"})
            }
            if(!material_id ||  material_id == 0)
                material_id =  3756
            // switch(topcate){
            //     case "综合":
            //         material_id = 3756
            //
            // }
            macId  = sea.getMd5(macId)
            client.execute('taobao.tbk.dg.optimus.material', {
                'page_size':pagesize,
                'adzone_id':mm,
                'page_no': page,
                'material_id':material_id,
                'device_value':macId,
                'device_encrypt':"MD5",
                'device_type':"UTDID",
            }, function(error, resInfo) {
                if (!error) {
                    resInfo  = utils.changeToObj(resInfo)
                    // console.log("resInfo",resInfo)
                    if(!resInfo.result_list.map_data){
                        return cb({msg:"没有数据",code:500})
                    }
                    var gaoyongRes = resInfo.result_list.map_data
                    // console.log("gaoyongRes",gaoyongRes)
                    for(var i = 0;i < gaoyongRes.length;i++){
                        console.log("gaoyongRes[i].commission_rate ",global.rate,global.rate,gaoyongRes[i].commission_rate )
                        gaoyongRes[i].commission_rate =  Math.round(gaoyongRes[i].commission_rate * 100 * global.rate * 0.9);
                        console.log("gaoyongRes[i].commission_rate ",gaoyongRes[i].commission_rate )
                        delete(gaoyongRes[i].click_url)
                        delete( gaoyongRes[i].coupon_click_url)
                        delete( gaoyongRes[i].coupon_end_time)
                        delete( gaoyongRes[i]["coupon_start_time"])
                        delete( gaoyongRes[i]["coupon_start_fee"])
                        delete( gaoyongRes[i]["coupon_total_count"])
                        delete( gaoyongRes[i]["item_description"])
                        delete( gaoyongRes[i]["level_one_category_name"])
                        delete( gaoyongRes[i]["level_one_category_id"])
                        delete( gaoyongRes[i]["seller_id"])
                    }

                    return cb({code:200,info:gaoyongRes})
                } else {
                    console.error("hotProducts err is",error);
                    return cb({msg:"没有数据",code:500})
                }
            })

            // let url = "http://api.vephp.com/products?"
            // let obj = {
            //     page,
            //     pagesize,
            //     vekey
            // };
            //
            // if(subcate){
            //     obj.subcate = subcate
            // }
            // if(topcate){
            //     obj.topcate = topcate;
            // }
            // if (sort){
            //     obj.sort = sort;
            // }
            //
            //
            // let gaoyongRes = await  RequestGet(url,obj);
            // // console.log(" gaoyongRes is:",gaoyongRes)
            // gaoyongRes = utils.changeToObj(gaoyongRes)
            // console.log(" gaoyongRes is:",gaoyongRes)
            // if(gaoyongRes.data && gaoyongRes.data.length >0 ){
            //     for(var i = 0;i < gaoyongRes.data.length;i++){
            //         gaoyongRes.data[i].commission_rate =  Math.round(gaoyongRes.data[i].commission_rate * 100 * global.rate);
            //     }
            //     return cb({code:200,info:gaoyongRes.data})
            // }else {
            //     return cb({msg:"没有数据",code:500})
            // }

        }catch(e){

        }
    }

    async clientTable(req, res, body, cb) {
        try {
            let key = body.key;
            if(!key){
                return cb({code:500,msg:"参数不足"})
            }
            let tableInfo = await sqlOrm.clientTable.findAsync({key:key})
            if(tableInfo.length >0 ){
                return cb({code:200,info:tableInfo[0].value})
            }else {
                return cb({msg:"没有数据",code:500})
            }
        }catch(e){

        }
    }

    async sonInfo(req, res, body, cb) {
        try {
            let account = body.account;
            if(!account){
                return cb({code:500,msg:"参数不足"})
            }
            let sumNum = await sqlOrm.connectionLocalhot.execQueryAsync( "SELECT count(account ) sumNum FROM  app_account   WHERE shareId = ?", [ account])
            let sonInfo = await sqlOrm.connectionLocalhot.execQueryAsync( "SELECT IF( sum(mayPay)/10 > 1 ,ROUND(sum(mayPay)/10), 0)  sumMoney FROM taobaokeorde t1, app_account t2  WHERE t2.shareId = ?  and t1.userId = t2.account  and  share = 1 and payStatusCode = 1", [ account])
            console.log("sumNum",sumNum)
            var info = {
                countNum:0,
                sumMoney:0,
            };
            if(sumNum.length > 0)  info.countNum = sumNum[0].sumNum
            if(sonInfo.length > 0)  info.sumMoney = sonInfo[0].sumMoney

            return cb({code:200,info:info})

        }catch(e){
            console.error(" sonInfo e ",e)
        }
    }

    async sonDetail(req, res, body, cb) {
        try {
            let account = body.account;
            if(!account){
                return cb({code:500,msg:"参数不足"})
            }
            let sonInfo = await sqlOrm.connectionLocalhot.execQueryAsync( "SELECT t1.account ,t1.createTime ,  IF( sum(t2.maypay)/10 > 1 ,ROUND(sum(t2.maypay)/10), 0)money  FROM app_account t1 LEFT JOIN taobaokeorde t2  on t1.account = t2.userId  WHERE t1.shareid =  ?  GROUP BY t1.account", [account])

            if(sonInfo.length >0 ){
                return cb({code:200,info:sonInfo})
            }else {
                return cb({msg:"没有数据",code:500 ,info:[]})
            }
        }catch(e){
            console.error(" sonDetail e ",e)
            return cb({msg:"没有数据",code:500})
        }
    }


}



async function login(lgToken) {
    var loginTime
    let params = {
        'lgToken': lgToken,
        'defaulturl': "http://www.alimama.com",
        '_ksTS': new Date().getTime(),
    };

    let headers = {
        'authority': 'qrlogin.taobao.com',
        'method': 'GET',
        'path': '/qrcodelogin/qrcodeLoginCheck.do?lgToken={lgToken}&defaulturl=http%3A%2F%2Fwww.alimama.com&_ksTS=' + new Date().getTime(),
        'referer': 'https://login.taobao.com/member/login.jhtml?style=mini&newMini2=true&css_style=alimama&from=alimama&redirectURL=http%3A%2F%2Fwww.alimama.com&full_redirect=true&disableQuickLogin=true',
    };

    let url = 'https://qrlogin.taobao.com/qrcodelogin/qrcodeLoginCheck.do?';
    let body = await  RequestGet(url, params, headers);
    body = utils.changeToObj(body)
    // console.log("body is:", body);

    var code = body.code;
    console.log(body) // Show the HTML for the baidu homepage.
    console.log("code :", code);
    lastCode = code
    if (code == 10004) {
        loginFlag = 0
        // 发送短信通知超时
        await utils.sentMsgInfo(18205960269, 'SMS_147970724');
        await utils.sentMsgInfo(18695611291, 'SMS_147970724');
    } else if (code != 10006) {
         loginTime = setTimeout(function () {
            login(lgToken)
        }, 2000)
    } else {
        console.log("登录成功：地址", body)
        clearTimeout(loginTime)
        var ans = await openUrl(body.url)
    }
}

var openUrl = async function (url) {

    var driver = new webdriver.Builder()

        .forBrowser('firefox')
        .build();
    var loginUrl = url;

    // "https://login.taobao.com/member/loginByIm.do?uid=cntaobao%E7%81%B0%E7%BE%BD%E7%B2%BE%E7%81%B5&token=ba26ab5022fa95f7c009639f6735bca0&time=1536417231337&asker=qrcodelogin&ask_version=1.0.0&defaulturl=https%3A%2F%2Fwww.taobao.com&webpas=d3b33103f639f096498c15c8e2328067889948548"
    driver.get(loginUrl)
        .then(function () {
            sleep(8000)
            driver.navigate().to('http://pub.alimama.com/');

            console.log("跳转阿里妈妈")
        })
        .then(function () {
            setTimeout(async function () {
                return driver.manage().getCookies().then(async function (cookies) {
                    console.log("cookies  isssssss", cookies);
                    var map = buildCookieMap(cookies);
                    var cookie2 = map.cookie2.value;
                    var _tb_token_ = map._tb_token_.value;
                    var t = map.t.value;
                    global.cookie2 = cookie2;
                    global.token = _tb_token_;
                    global.t = t;
                    global.cookies = cookies;

                    let cookie2Sql = await sqlOrm.global.findAsync({id:2})
                    let tokenSql = await sqlOrm.global.findAsync({id:3})

                    cookie2Sql[0].value =cookie2
                    tokenSql[0].value =token

                    await  cookie2Sql[0].saveAsync();
                    await  tokenSql[0].saveAsync();
                    let b = await  RequestGet(changeGlobalUrl, {});
                    // setTimeout(function () {
                    driver.quit()
                    loginFlag = 0
                    // }, 1000 * 60 * 10)

                });
            }, 1000 * 10)
        })
}

var findUrlByThAPI = async function (mmUser, itemId, phone, cb) {
    var  mmT = mm;
    if (mmUser) {
        mmT = mmUser
    }
    let pid = "mm_68895478_112300025_" + mmT;
    let gaoyongInfo = await  RequestGet("http://api.vephp.com/hcapi?",{vekey:vekey,para:itemId,pid:pid,detail:1,noshortlink :1})
    console.log("gaoyongInfo",gaoyongInfo)
    gaoyongInfo = utils.changeToObj(gaoyongInfo);
    if (gaoyongInfo && !gaoyongInfo.error){
        gaoyongInfo.data.coupon_share_url = gaoyongInfo.data.coupon_click_url;
        gaoyongInfo.data.commission_rate = gaoyongInfo.data.commission_rate * 100;

        if(gaoyongInfo.data.coupon_info){
            var startP = gaoyongInfo.data.coupon_info.indexOf("减");
            gaoyongInfo.data.coupon_info = gaoyongInfo.data.coupon_info.substring(startP + 1, gaoyongInfo.data.coupon_info.length - 1);
        }
        gaoyongInfo.data.commission_rate = Math.floor(gaoyongInfo.data.commission_rate)

        var tbk_pwd  = gaoyongInfo.data.tbk_pwd;
        var coupon_short_url =  gaoyongInfo.data.coupon_short_url;
        var zk_final_price =  gaoyongInfo.data.zk_final_price;

        gaoyongInfo.data.tbk_pwd = tbk_pwd;
        gaoyongInfo.data.coupon_short_url = coupon_short_url;
        gaoyongInfo.data.zk_final_price = zk_final_price;
        gaoyongInfo.data.phone = 0;
        gaoyongInfo.data.url = coupon_short_url;
        gaoyongInfo.data.nick = JSON.stringify(gaoyongInfo.data.nick)
        // gaoyongInfo.data.assign(tbk_pwd)


        console.log("gaoyongInfo",gaoyongInfo)
         cb(gaoyongInfo.data)
        try {
            await  sqlOrm.taobaoitem.createAsync(gaoyongInfo.data);
        }catch (e){
            console.info("重复物品或者存库失败",itemId)
        }
        return
    }else {
        console.error("没有推广物品",itemId)
        return cb(0)
    }
}


var findUrlByAPI = function (mmUser, itemId, phone, cb) {
    var q = "https://item.taobao.com/item.htm?id=" + itemId;
    var  mmT = mm
    if (mmUser) {
         mmT = mmUser
    }
    client.execute('taobao.tbk.dg.material.optional', {
        'cat': '>',
        'q': q,
        'adzone_id': mmT,
    }, async function (error, response) {
        if (!error) {
            if (response.result_list && response.result_list.map_data.length > 0) {
                for (let tbk_coupon of response.result_list.map_data) {
                    var startP = tbk_coupon.coupon_info.indexOf("减");
                    tbk_coupon.coupon_info = tbk_coupon.coupon_info.substring(startP + 1, tbk_coupon.coupon_info.length - 1);

                    // if (tbk_coupon.coupon_share_url && tbk_coupon.coupon_share_url.length > 0) tbk_coupon.coupon_share_url = "http:" + tbk_coupon.coupon_share_url
                    // if (tbk_coupon.url && tbk_coupon.url.length > 0) tbk_coupon.url = "http:" + tbk_coupon.url

                    tbk_coupon.phone = phone
                    // tbk_coupon.mm = mmT
                    console.log("tbk_coupon", tbk_coupon)

                    // http://api.vephp.com/hcapi?vekey=V00000355Y39162829&para=17241546606&pid=mm_68895478_112300025_36418400326
                    let pid = "mm_68895478_112300025_" + mmT
                    let gaoyongInfo = await  RequestGet("http://api.vephp.com/hcapi?",{vekey:vekey,para:itemId,pid:pid})

                    gaoyongInfo = utils.changeToObj(gaoyongInfo);
                    if (gaoyongInfo && !gaoyongInfo.error){
                        tbk_coupon.coupon_share_url = gaoyongInfo.data.coupon_click_url;
                        tbk_coupon.commission_rate = gaoyongInfo.data.commission_rate * 100;
                        var tbk_pwd  = gaoyongInfo.data.tbk_pwd;
                        var coupon_short_url =  gaoyongInfo.data.coupon_short_url;
                    }
                    tbk_coupon.commission_rate = Math.floor(tbk_coupon.commission_rate)
                    try {
                        await  sqlOrm.taobaoitem.createAsync(tbk_coupon);
                    }catch (e){
                        console.info("重复订单")
                    }
                    tbk_coupon.tbk_pwd = tbk_pwd;
                    tbk_coupon.coupon_short_url = coupon_short_url;
                    if (tbk_coupon.num_iid == itemId) {
                        return cb(tbk_coupon)
                    }
                }
            }else {
                return cb(0)
            }

        } else {
            console.error("查询错误", error);
            return cb(0)
        }
    })
}


var findUrlByAPIMsg = async function (mmUser, msg, phone,page_no,page_size,sortType,coupon ,start_price,end_price,cb) {
    try {

        var  mmT = mm
        if (mmUser) {
            mmT = mmUser
        }
        let obj ={
            page:page_no,
            pagesize:page_size,
            coupon:coupon,
            sort :sortType,
            start_price  :start_price ,
            end_price   :end_price  ,
            vekey   :vekey  ,
            para   :msg  ,
        }
        let url = `http://apis.vephp.com/super?`
        let Items = await RequestGet(url,obj);
        console.log("Items",Items)
        Items = utils.changeToObj(Items)
        if(Items.data && !Items.result_list){
            Items.result_list = [];
            Items.data.commission_rate  = Items.data.commission_rate * 100
            Items.result_list.push(Items.data)
        }
        for(var i=0;i< Items.result_list.length;i++ ){
            let tbk_coupon = Items.result_list[i]
            // console.log("tbk_coupon.tbk_coupon",tbk_coupon)
            if(tbk_coupon.coupon_info){
                var startP = tbk_coupon.coupon_info.indexOf("减");
                tbk_coupon.phone = phone
                tbk_coupon.coupon_info = tbk_coupon.coupon_info.substring(startP + 1, tbk_coupon.coupon_info.length - 1);
            }
            tbk_coupon.commission_rate = utils.changeToObj(tbk_coupon.commission_rate)
            tbk_coupon.commission_rate =  tbk_coupon.commission_rate  * 0.9 * global.rate
            tbk_coupon.commission_rate = Math.floor(tbk_coupon.commission_rate);
            }
        return cb(Items.result_list)
    }catch (e){
        console.error("查询错误", e);
        return cb(0)
    }

    // client.execute('taobao.tbk.dg.material.optional', {
    //     'cat': '>',
    //     'q': msg,
    //     'adzone_id': mmT,
    //     "page_no":page_no,
    //     "page_size":page_size,
    //     "sort":sortType,
    //
    // }, async function (error, response) {
    //     if (!error) {
    //         if (response.result_list && response.result_list.map_data.length > 0) {
    //             for (let tbk_coupon of response.result_list.map_data) {
    //                 var startP = tbk_coupon.coupon_info.indexOf("减");
    //                 tbk_coupon.coupon_info = tbk_coupon.coupon_info.substring(startP + 1, tbk_coupon.coupon_info.length - 1);
    //
    //                 if (tbk_coupon.coupon_share_url && tbk_coupon.coupon_share_url.length > 0) tbk_coupon.coupon_share_url = "http:" + tbk_coupon.coupon_share_url
    //                 if (tbk_coupon.url && tbk_coupon.url.length > 0) tbk_coupon.url = "http:" + tbk_coupon.url
    //
    //                 tbk_coupon.phone = phone
    //                 console.log("tbk_coupon", tbk_coupon)
    //                 let pid = "mm_68895478_112300025_" + mmT
    //                 let gaoyongInfo = await  RequestGet("http://api.vephp.com/hcapi?",{vekey:vekey,para:tbk_coupon.num_iid,pid:pid})
    //                 gaoyongInfo = utils.changeToObj(gaoyongInfo);
    //                 if (gaoyongInfo && !gaoyongInfo.error){
    //                     tbk_coupon.coupon_share_url = gaoyongInfo.data.coupon_click_url;
    //                     tbk_coupon.commission_rate = gaoyongInfo.data.commission_rate * 100;
    //                 }
    //                 tbk_coupon.commission_rate = Math.floor(tbk_coupon.commission_rate);
    //
    //                 try {
    //                      sqlOrm.taobaoitem.createAsync(tbk_coupon);
    //                 }catch (e) {
    //                     console.error("errrrr",e)
    //                 }
    //             }
    //             return cb(response.result_list.map_data)
    //         }else {
    //             return cb(0)
    //         }
    //
    //     } else {
    //         console.error("查询错误", error);
    //         return cb(0)
    //     }
    // })
}






function buildCookieMap(cookies) {

    var map = {};

    cookies.forEach(function (cookie) {

        map[cookie.name] = cookie;

    });

    return map;

}

function sleep(d) {
    for (var t = Date.now(); Date.now() - t <= d;) ;
}

async function GetPingDDUrl(itemId,userId,accountInfo,cb){
    try {
        let tuiGuangurl = await getPddItemUrl(itemId,userId,accountInfo);
        let ItemDetail =  await getPddItemDetail(itemId,userId,accountInfo)

        if(!tuiGuangurl || !ItemDetail){
            return cb({code: 202, info: {}, msg: "暂时没有录入"})
        }

        let res = {};
        res.commission_rate = ItemDetail[0].promotion_rate
        res.commission_rate = utils.changeToObj(res.commission_rate) * 10
        res.commission_rate =  res.commission_rate  * 0.9 * global.rate
        res.commission_rate =  Math.floor(res.commission_rate)

        res.coupon_info = ItemDetail[0].coupon_discount/100
        res.coupon_short_url = tuiGuangurl[0].short_url

        res.title = ItemDetail[0].goods_name
        res.zk_final_price = ItemDetail[0].min_group_price/100
        res.we_app_web_view_url = tuiGuangurl[0].we_app_web_view_url

        res.tbk_pwd = tuiGuangurl[0].mobile_short_url  //拼多多没有？ 用唤起微信app推广短链接
        res.url = tuiGuangurl[0].short_url  //info.coupon_short_url  暂时不需要短链接
        return cb({code: 200, info: res})
    }catch (e){
        console.error("GetPingDDUrl err ",e)
        return cb({code: 202, info: {}, msg: "暂时没有录入"})
    }


}

async function GetTaobaoUrl(itemId, userId,accountInfo,cb){
    let mm = accountInfo[0].mm;
    // let SqlUrl = await sqlOrm.taobaoitem.findAsync({num_iid: itemId, phone: userId});
    // console.log("SqlUrl is", SqlUrl.length)
    // console.log("SqlUrl is", SqlUrl)
    var info;
    // if (SqlUrl.length > 0) {
    //     info = SqlUrl[0]
    //     // info.commission_rate = info.commission_rate * 0.9 * global.rate;
    //     let res = {};
    //     res.commission_rate = info.commission_rate
    //     res.commission_rate =  res.commission_rate  * 0.9 * global.rate
    //     res.commission_rate =  Math.floor(res.commission_rate)
    //     res.coupon_info = info.coupon_info
    //     res.url = info.coupon_share_url
    //     if (!res.url) {
    //         res.url = info.url
    //     }
    //     return cb({code: 200, info: res})
    // } else {
    //     console.log("数据库没有信息调用aip");
    findUrlByThAPI(mm, itemId, userId, function (findUrlByAPIRes) {
        // console.log("API信息", findUrlByAPIRes);
        if (findUrlByAPIRes != 0) {

            info = findUrlByAPIRes
            console.log("findUrlByAPIRes",info)
            //info.commission_rate = findUrlByAPIRes.commission_rate * 0.9 * global.rate;
            let res = {};
            //console.log(" info is ",info)
            res.commission_rate = info.commission_rate
            // console.log("res", res)
            // console.log("res.commission_rate", res.commission_rate)
            res.commission_rate = utils.changeToObj(res.commission_rate)
            res.commission_rate =  res.commission_rate  * 0.9 * global.rate
            res.commission_rate =  Math.floor(res.commission_rate)
            res.coupon_info = info.coupon_info
            res.coupon_short_url = info.coupon_short_url
            res.title = info.title
            res.zk_final_price = info.zk_final_price
            res.tbk_pwd = info.tbk_pwd
            res.url = info.coupon_share_url  //info.coupon_short_url  暂时不需要短链接
            // console.log("res.rul is", res.url)
            if (!res.url || (res.url).length <= 1) {
                res.url = findUrlByAPIRes.url
            }
            return cb({code: 200, info: res})
        }
        if (!info) {
            console.log("还是没有表示该物品没有推广");
            return cb({code: 202, info: {}, msg: "暂时没有录入"})
        }
    })
}

async function getPddItemUrl(itemId, userId,accountInfo){

    try {

        let postUrl = "http://gw-api.pinduoduo.com/api/router";
        let postVaule = {
            'client_id': `${config.client_id}`,
            'type': 'pdd.ddk.goods.promotion.url.generate',
            'timestamp': `${Math.floor(new Date().getTime()/1000)}`,
            'data_type': 'JSON',
            'goods_id_list': "" + [JSON.parse(itemId)],
            'p_id': `${config.p_id}`,
        };

        let SignStr = utils.MakeStr(postVaule);
        let sign = utils.PDDSign(SignStr);
        postVaule.sign = sign;
        postVaule.goods_id_list = "[" + JSON.parse(itemId) + "]";

        let resInfo = await RequestPost(postUrl,postVaule);
        console.log("resInfo is:",resInfo);
        if(resInfo && resInfo.goods_promotion_url_generate_response && resInfo.goods_promotion_url_generate_response.goods_promotion_url_list.length > 0){
            console.log("resInfo is:",resInfo.goods_promotion_url_generate_response.goods_promotion_url_list);
            return resInfo.goods_promotion_url_generate_response.goods_promotion_url_list
        }
        return null
    }catch (e) {
        return null
    }

}
async function getPddItemDetail(itemId, userId,accountInfo){

    try {

        let postUrl = "http://gw-api.pinduoduo.com/api/router";
        let postVauleDetail = {
            'client_id': `${config.client_id}`,
            'type': 'pdd.ddk.goods.detail',
            'timestamp': `${Math.floor(new Date().getTime()/1000)}`,
            'data_type': 'JSON',
            'goods_id_list': "" + [JSON.parse(itemId)],
        };

        let SignStrDetail = utils.MakeStr(postVauleDetail);
        let sign = utils.PDDSign(SignStrDetail);
        postVauleDetail.sign = sign;
        postVauleDetail.goods_id_list = "[" + JSON.parse(itemId) + "]";

        console.log("postVauleDetail is:",postVauleDetail);
        let resInfoDetail = await RequestPost(postUrl,postVauleDetail);
        console.log("resInfoDetail is:",resInfoDetail);
        if(resInfoDetail && resInfoDetail.goods_detail_response && resInfoDetail.goods_detail_response.goods_details.length > 0){
            console.log("resInfo is:",resInfoDetail.goods_detail_response.goods_details);
            return  resInfoDetail.goods_detail_response.goods_details
        }
        return null
    }catch (e) {
        console.error("getPddItemDetail err is :",e)
        return null
    }
}



module.exports = new Register();


